package com.learn.security.configuration;

import com.learn.security.service.AuthService;
import com.learn.security.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@PropertySource("classpath:security.properties")
@ComponentScan(basePackages={"com.learn.security.service"})
@EnableJpaRepositories(basePackages = "com.learn.security.repository")
@EntityScan(basePackages = {"com.learn.security.entity"})
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

//    @Autowired
//    private AdminService adminService;

    @Autowired
    private AuthService authService;

//    @Override
//    public void configure(WebSecurity web) throws Exception {
//        web.ignoring().antMatchers(HttpMethod.POST);
//    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/list").hasAuthority("Administrator")
                .antMatchers("/test").hasAuthority("Admin")
//                .antMatchers("**/**","/","**").permitAll()
                .anyRequest().authenticated()
                .and().formLogin().usernameParameter("userName").passwordParameter("password")
                .loginPage("/admin/login").defaultSuccessUrl("/admin/home").permitAll()
                .and().logout().logoutUrl("/admin/logout").logoutSuccessUrl("/admin/login").permitAll()
                .and().httpBasic()
//                .and().exceptionHandling().accessDeniedPage("/Access_Denied")
                .and().csrf().disable();
    }

    @Autowired
    public void configure(AuthenticationManagerBuilder builder) throws Exception{
//        builder.userDetailsService(adminService)
//            .passwordEncoder(passwordEncoder());
        builder.authenticationProvider(authService);
    }

    /**
     * 设置用户密码的加密方式为MD5加密
     * @return
     */
    @Bean
    public Md5PasswordEncoder passwordEncoder() {
        return new Md5PasswordEncoder();
    }

}
